﻿/*
 * 日历型热图
 */
define(function (require, exports, module) {
    var modules = {
        colorHelper: require('../../util/colorHelper'),
        ObjectHelper: require('../../util/objecthepler')
    }
    var buildChart = function (svgSelector, data, columnFields, rowFields, options) {
        //取得日期维度字段
        var dateField = columnFields.find(function (d) { return d.slaveType === 0 && d.dataType === 4; }) || rowFields.find(function (d) { return d.slaveType === 0 && d.dataType === 4; });
        var measureField = columnFields.find(function (d) { return d.slaveType === 1; }) || rowFields.find(function (d) { return d.slaveType === 1; });
        //必须存在日期维度、日期细分为支持的模式、度量、数据不为空
        if (!dateField || dateField.DateTimeSub !== "_ymd" || !measureField || !data || data.length === 0) {
            return false;
        }
        var years = [];
        var _lastYear = 0;

        var config=options.chartConfig;
        if(!config){
            config={
                GlobalColor: "#4E79A7",
                scale: 0.8,
                axisStyle: {
                    tickColor : "#000",
                    fontColor : "#000",
                    fontFamily: "Arial",
                    fontSize  : 12
                },
                textStyle: {
                    "display"     : "none",
                    "font-family" : "Arial",
                    "font-size"   : 12,
                    "font-style"  : "normal",
                    "font-weight" : "normal",
                    "fill"        : "#333",
                    "position"    : "top"
                }
            }
        }
         var globalcolor=config.GlobalColor;
        //整理数据
        Enumerable.from(data).orderBy(function (d) { return d[dateField.name]; }).forEach(function (d) {
            d["_date_"] = d3.parseDateTime(d[dateField.name], "%Y%m%d");
            d["_year_"] = d["_date_"].getFullYear();
            if (_lastYear !== d["_year_"]) {
                years.push(d["_year_"]);
                _lastYear = d["_year_"];
            }
        });
        years.sort();
        //构建图表
        var chart_opt = {
            visualMap: {
                min: Enumerable.from(data).min(function (d) { return d[measureField.name]; }),
                max: Enumerable.from(data).max(function (d) { return d[measureField.name]; }),
                calculable: true,
                orient: 'horizontal',
                left: 'center',
                top: 'top',
                inRange: {
                    color: [colorHelper.calc_gradient_color(globalcolor, 100, 10), globalcolor]
                },
                textStyle:{
                    color:config.axisStyle.fontColor
                }
            },
            calendar: [],
            series: [],
            _dateField: dateField,
            _measureField: measureField,
            _TooltipFormat: options.TooltipFormat
        }
        years.forEach(function (year, idx) {
            chart_opt.calendar.push({
                top: 160 * idx + 60,
                range: year.toString(),
                cellSize: ["auto", 20],
                dayLabel: { nameMap: 'cn',color:config.axisStyle.fontColor },
                monthLabel: { nameMap: "cn",color:config.axisStyle.fontColor },
                yearLabel:{color:config.axisStyle.fontColor}
            });
            var _data = data.filter(function (d) { return d["_year_"] === year; }).map(function (d) {
                return [d["_date_"], d[measureField.name]];
            });
            chart_opt.series.push({
                type: 'heatmap',
                coordinateSystem: 'calendar',
                calendarIndex: idx,
                data: _data
            });
        });
        var dom_container = $(svgSelector).children('#chart')[0];
        var chartInstance = new chart(dom_container, chart_opt);
        return chartInstance;
    }
    var chart = function (dom_container, opt) {
        var self = this;
        var myChart = echarts.init(dom_container);
        var chart_opt = {
            tooltip: {
                position: 'top',
                formatter: function (params, ticket, callback) {
                    var date = params.data[0];
                    var value = params.data[1] || 0;
                    var content = chart_opt._TooltipFormat;
                    if (!content) {
                        content = chart_opt._dateField.name + ":" + new Date(date).format("yyyy-MM-dd") + "<br>" + chart_opt._measureField.name + ":" + value.toMeasureFormart(chart_opt._measureField.numberFormat);
                    } else {
                        chart_opt._dateField.value=new Date(date).format("yyyy-MM-dd");
                        chart_opt._measureField.value=value.toMeasureFormart(chart_opt._measureField.numberFormat);
                        var fields=[chart_opt._dateField, chart_opt._measureField];
                        fields.forEach(function (field) {
                            var pattern = field.name.replace(/\(/g, "\\(").replace(/\)/g, "\\)");
                            var reg = new RegExp("<" + pattern + ">", "g");
                            content = content.replace(reg, field.value);
                        });
                        content = content.replace(/\n/g, "<br>");
                    }
                    return content;
                }
            },
            //brush: {
            //    toolbox: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
            //    throttleType:"debounce"
            //},
            calendar: [],
            series: []
        }
        var setOption = function (opt) {
            chart_opt = $.extend(chart_opt, opt);
            var totalheight = opt.calendar.length * 160 + 60;
            if (totalheight > $(dom_container).height()) {
                $(dom_container).find("canvas").height(totalheight);
            }
            myChart.setOption(chart_opt);
        }
        if (opt) {
            setOption(opt);
        }
        //响应点击事件
        myChart.on("click", function (args) {
            if (args.componentType === "series") {
                var calldata = [{
                    field: chart_opt._dateField,
                    value: [args.data[0].format("yyyyMMdd")]
                }];
                if (self.onselected) {
                    self.onselected(calldata);
                }
            }
        });
        //响应框选事件
        myChart.on('brushSelected', function (args) {
            modules.ObjectHelper.delayExecute(function () {
                console.log(args);
            }, 200);
        });
        this.setOption = setOption;
        this.removeChart = function () {
            myChart.dispose();
        }
        this.tipFormat=function(format){
            chart_opt._TooltipFormat=format;
        }
    }
    module.exports = {
        build: buildChart
    }
});
